package dongze.com.ckdj.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import dongze.com.ckdj.activity.CheckInOperationItemSelectionActivity;
import dongze.com.ckdj.adapter.ListItem;
import dongze.com.ckdj.adapter.VehicleInformationAdapter;
import dongze.com.ckdj.data.entity.response.InspectionSectionRecordDetailResponse;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/7/21.
 */

public class CheckInOperationRecordFragment extends ProcessableFragment implements AdapterView.OnItemClickListener {
    private static final String TAG = CheckInOperationRecordFragment.class.getSimpleName();
    private static final int REQUEST_EDIT_ITEM = 2059;
    ListView mOperationList;
    String id;
    List<InspectionSectionRecordDetailResponse> recordDetailResponses;
    ListItem[] listItems;
    InspectionSectionRecordDetailResponse currentRecordDetailResponse;

    public void setID(String id) {
        this.id = id;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (id != null)
            loadRecordDetail(id);
    }

    @Nullable
    @Override
    protected View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mOperationList = new ListView(container.getContext());
        mOperationList.setOnItemClickListener(this);
        return mOperationList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void loadRecordDetail(String id) {
        doProcessing();
        mapUtil.getInspectionSectionRecordDetail(id,
                new DisposableObserver<Pair<List<InspectionSectionRecordDetailResponse>, List<ListItem>>>() {
                    @Override
                    public void onNext(Pair<List<InspectionSectionRecordDetailResponse>, List<ListItem>> value) {
                        recordDetailResponses = value.first;
                        VehicleInformationAdapter adapter = new VehicleInformationAdapter();
                        listItems = new ListItem[value.second.size()];
                        value.second.toArray(listItems);
                        adapter.setListItems(listItems);
                        mOperationList.setAdapter(adapter);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        finishProcessing();
                    }

                    @Override
                    public void onComplete() {
                        finishProcessing();
                    }
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        if (recordDetailResponses != null && recordDetailResponses.get(position) != null) {
//            currentRecordDetailResponse = recordDetailResponses.get(position);
//            Intent intent = new Intent(view.getContext().getApplicationContext(), CheckInOperationItemSelectionActivity.class);
//            intent.putExtra("key", currentRecordDetailResponse.getProgram_name());
//            intent.putExtra("value", currentRecordDetailResponse.getProgram_value());
//            startActivityForResult(intent, REQUEST_EDIT_ITEM);
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_EDIT_ITEM) {
            if (resultCode == Activity.RESULT_OK) {
                String key = data.getStringExtra("key");
                final String value = data.getStringExtra("value");

                if (!TextUtils.isEmpty(key)) {
                    for (final ListItem i :
                            listItems) {
                        if (TextUtils.equals(i.getKey(), key)) {
                            new AlertDialog.Builder(getContext())
                                    .setMessage("是否上传修改到服务器？")
                                    .setNegativeButton("不上传", null)
                                    .setPositiveButton("上传", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            commitChange(i, value);
                                        }
                                    })
                                    .create()
                                    .show();

                            break;
                        }
                    }
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void commitChange(final ListItem item, final String value) {
        if (item != null && currentRecordDetailResponse != null) {
            if (TextUtils.equals(item.getKey(), currentRecordDetailResponse.getProgram_name())) {
                mapUtil.modifyCheckInRecord(currentRecordDetailResponse.getRecord_detail_id(), value, new DisposableObserver<String>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        doProcessing();
                    }

                    @Override
                    public void onNext(String value) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        new AlertDialog.Builder(getContext())
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                        finishProcessing();
                    }

                    @Override
                    public void onComplete() {
                        Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
                        item.setValue(value);
                        ((VehicleInformationAdapter) mOperationList.getAdapter()).notifyDataSetChanged();
                        finishProcessing();
                    }
                });
            } else {
                Toast.makeText(getContext(), "key not equal", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
